/**
 * 参数直接在url的search中添加，不要在hash中加
 * 打开本地需要参数：{
 *  key: "", // 上传base64时携带的key
 * }
 */

import { Component } from 'react'
import { View } from '@tarojs/components'
import Taro, { Current } from '@tarojs/taro'
import { connect } from 'react-redux'
import SignatureCanvas from 'react-signature-canvas'
import { getBaseUrl } from '@/network/baseUrl'
import Utils from '@/utils/index'
import Proxy from '@/network/proxy'
import {tipAlert} from '../component/tipAlert'
import $ from 'jquery'
import Header from '@/pages/myComponent/header'
import './index.scss'

// 旋转图片（顺时针旋转）
export function rotateBase64Img(src, edg = 90) {
    return new Promise((resolve, reject) => {
        if (edg == 0) {
            resolve(src)
            return
        }
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        var imgW; //图片宽度
        var imgH; //图片高度
        var size; //canvas初始大小
        if (edg % 90 != 0) {
            console.error("旋转角度必须是90的倍数!");
            throw "旋转角度必须是90的倍数!";
        }
        edg < 0 && (edg = (edg % 360) + 360);
        const quadrant = (edg / 90) % 4; //旋转象限
        const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 }; //裁剪坐标
        var image = new Image();
        image.crossOrigin = "anonymous";
        image.src = src;
        image.onload = function () {
            imgW = image.width;
            imgH = image.height;
            size = imgW > imgH ? imgW : imgH;
            canvas.width = size * 2;
            canvas.height = size * 2;
            switch (quadrant) {
                case 0:
                    cutCoor.sx = size;
                    cutCoor.sy = size;
                    cutCoor.ex = size + imgW;
                    cutCoor.ey = size + imgH;
                    break;
                case 1:
                    cutCoor.sx = size - imgH;
                    cutCoor.sy = size;
                    cutCoor.ex = size;
                    cutCoor.ey = size + imgW;
                    break;
                case 2:
                    cutCoor.sx = size - imgW;
                    cutCoor.sy = size - imgH;
                    cutCoor.ex = size;
                    cutCoor.ey = size;
                    break;
                case 3:
                    cutCoor.sx = size;
                    cutCoor.sy = size - imgW;
                    cutCoor.ex = size + imgH;
                    cutCoor.ey = size + imgW;
                    break;
            }
            ctx.translate(size, size);
            ctx.rotate((edg * Math.PI) / 180);
            ctx.drawImage(image, 0, 0);
            var imgData = ctx.getImageData(
                cutCoor.sx,
                cutCoor.sy,
                cutCoor.ex,
                cutCoor.ey
            );
            if (quadrant % 2 == 0) {
                canvas.width = imgW;
                canvas.height = imgH;
            } else {
                canvas.width = imgH;
                canvas.height = imgW;
            }
            ctx.putImageData(imgData, 0, 0);
            resolve(canvas.toDataURL())
        };
    })
}
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            canvasRotate: 270, // canvas旋转的角度

            canvasWidth: 0,
            canvasHeight: 0,

        };
    }
    canvasRef = null // 保存canvas的引用


    componentDidMount() {
        // 确保元素已经渲染，能获取dom节点
        setTimeout(() => {
            this.calcCanvasWH();
        }, 200);
    }
    // 获取并设置canvas的宽高
    calcCanvasWH = () => {
        let indexDom = document.querySelector(".my_index");
        let btnsDom = document.querySelector(".btns");
        // mobile
        let canvasRotate = 270
        // PC || ipad
        if (indexDom.offsetWidth > indexDom.offsetHeight) { // 宽 > 高
            canvasRotate = 0
        }
        this.setState({ canvasRotate }, () => {
            let indexDom = document.querySelector(".my_index");
            let btnsDom = document.querySelector(".btns");
            // mobile
            let canvasWidth = indexDom.offsetWidth - btnsDom.offsetWidth - 2;
            let canvasHeight = indexDom.offsetHeight;
            // PC || ipad
            if (indexDom.offsetWidth > indexDom.offsetHeight) { // 宽 > 高
                canvasWidth = indexDom.offsetWidth
                canvasHeight = indexDom.offsetHeight - btnsDom.offsetHeight - 2
            }
            this.setState({
                canvasWidth,
                canvasHeight,
            }, () => {
                this.clearSign()
            })

        });
    };
    // 清空
    clearSign = () => {
        this.canvasRef.clear();
    };

    //base64图片转成文件流格式
    base64ToFile = (data, fileName = new Date().getTime()) => {
        if (!data) {
            return
        }
        const dataArr = data.split(",");
        const byteString = atob(dataArr[1]);
        const options = {
            type: "image/jpeg",
            endings: "native"
        };
        const u8Arr = new Uint8Array(byteString.length);
        for (let i = 0; i < byteString.length; i++) {
            u8Arr[i] = byteString.charCodeAt(i);
        }
        let fileOfBlob = new File([u8Arr], fileName + ".png", options);//返回文件流
        return fileOfBlob
    }
    uploadSign = (formData) => {
        let url = this.props.noticeAddr+ '/api/commons/file/mobile/batch/upload'

        if (Utils.getSystemInfo() === 'weapp') {
            url = Proxy.transmitUrlToVisit(url)
        }
        return new Promise((resolve, reject) => {
            $.ajax({
                url,
                type: "post",
                data: formData,
                async: true,
                dataType: 'json',
                headers: {
                    Authorization: Utils.getNowToken()
                },
                cache: false, // 上传文件无需缓存
                processData: false, // 使数据不做处理
                contentType: false, //不额外设置请求头
                success: (res) => {
                    if (res.code == 200 && res.data) {
                        resolve(res.data)
                    } else {
                        reject()
                    }
                },
            })
        })
    }
    // 确定
    confirm = async () => {
        let canvasRotate = this.state.canvasRotate
        console.log(tipAlert)
        if (this?.canvasRef?.isEmpty()) {
            tipAlert.show({
                content: "签名不可为空",
                icon: "error",
                key: "tip",
                className: canvasRotate != 0 ? "tipAlert_rotate" : ""
            })
            return
        }
        let key = Current.router?.params.key
        let base64 = this.canvasRef?.toDataURL();
        base64 = await rotateBase64Img(base64, canvasRotate)

        let formData = new FormData();   // 创建一个formData对象
        formData.append("file", this.base64ToFile(base64));    // 给这个对象添加键值对
        let file = await this.uploadSign(formData)
        const sign = file[0]?.url || "";
        Taro.showToast({
            title: "上传签名成功"
        })

        const route=Current.router.params || {}
        const {id="",taskReleaseId=""}=route
        const noticeAddr=this.props.noticeAddr
        const userInfo=this.props.userInfo || {}
        Taro.eventCenter.trigger("confirmWithSign", sign,id,taskReleaseId=="undefined"?"":taskReleaseId,noticeAddr,userInfo);
        setTimeout(() => {
            Taro.navigateBack()
        }, 100);
    };
    render() {
        let { canvasWidth, canvasHeight, canvasRotate } = this.state;
        return (
            <View className={`my_index ${canvasRotate != 0 ? "rotate_index" : ""}`}>
                {/* <View className='sign_header'>
                    <View className=''></View>
                    <View className='text'>签名</View>
                </View> */}
                <SignatureCanvas
                    penColor="#000"
                    backgroundColor="#f7f7f7"
                    ref={(ref) => { this.canvasRef = ref; }}
                    canvasProps={{
                        width: canvasWidth,
                        height: canvasHeight,
                        className: "sigCanvas",
                    }}
                />
                <View className="btns">
                    <View className="btn" onClick={() => { Taro.navigateBack() }}>
                        返回
                    </View>
                    <View className="yellow_btn btn" onClick={this.clearSign}>
                        清空签名
                    </View>
                    <View className="btn" onClick={this.confirm}>
                        确定签名
                    </View>
                </View>
            </View>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        userInfo: state.commonData.userInfo,
        noticeAddr:state.commonData.noticeAddr
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        setSign: (obj) => {
            dispatch({type:'SETSIGN',data:obj});
        },
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
